package com.mall.widget;

import android.content.Context;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.RelativeSizeSpan;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.examination.mlib.bean.HomeDrugEntity;
import com.examination.mlib.constants.AllStringConstants;
import com.examination.mlib.constants.ClickApi;
import com.examination.mlib.constants.KitArouterConstants;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.mall.MallUtils;
import com.mall.R;
import com.mall.observer.MallObserver;
import com.yilijk.base.network.RequestParams;
import com.yilijk.base.network.https.HttpCallBack;
import com.yilijk.base.network.https.HttpUtils;
import com.yilijk.base.utils.ALog;
import com.yilijk.base.utils.ClickUtils;
import com.yilijk.base.utils.GlideUtil;
import com.yilijk.base.utils.ListUtil;
import com.yilijk.base.utils.LoadingUtils;
import com.yilijk.base.utils.ToastUtils;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

public class MallDrugRecyclerView extends XRecyclerView implements XRecyclerView.LoadingListener {
    private Context context;
    private final List<HomeDrugEntity.DrugItemData> drugs = new ArrayList<>();
    private MallDrugAdapter adapter;
    private String id = "";
    private String doctorId = "";
    private int pageStart = 1;
    private int pageSize = 20;

    public MallDrugRecyclerView(Context context) {
        super(context);
        init(context);
    }

    public MallDrugRecyclerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public MallDrugRecyclerView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    private void init(Context context) {
        this.context = context;
        setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));

        adapter = new MallDrugAdapter(context, drugs);
        setAdapter(adapter);
        setPullRefreshEnabled(false);
        setLoadingMoreEnabled(true);
        setLoadingListener(this);
    }

    public void setData(String id, String doctorId) {
        this.id = id;
        this.doctorId = doctorId;
        pageStart = 1;
        drugs.clear();
        adapter.notifyDataSetChanged();
        getMallDrug(id);

    }


    private void getMallDrug(String id) {
        setLoadingMoreEnabled(false);
        LoadingUtils.getLoadingUtils(context).showLoading();
        RequestParams params = new RequestParams();
        params.put("pageIndex", pageStart);
        params.put("pageSize", pageSize);
        params.put("doctorId", this.doctorId);
//        params.put("frontCategoryId", "[" + id + "]");
        params.put("frontCategoryIds", id);
        params.put("scene", 1);
        params.put("containVirtualService", false);
//        ArrayList<String> ids = new ArrayList<>();
//        ids.add(id);
//        params.put("frontCategoryIds", ids);
        HttpUtils.get(AllStringConstants.MallUrl.waterfallFlowList, params, new HttpCallBack<HomeDrugEntity>() {
            @Override
            public void onSuccess(HomeDrugEntity bean, int i) {
                LoadingUtils.getLoadingUtils(context).dismissLoading();
                if (i == 200 && bean != null && bean.getCode() == 200 && bean.getData() != null) {
                    if (pageStart == 1) {
                        drugs.clear();
                    }
                    List<HomeDrugEntity.DrugItemData> listBeans = bean.getData().getDataList();
                    drugs.addAll(listBeans);
                    adapter.notifyDataSetChanged();
                    loadMoreComplete();
                    if (pageStart == 1) {
                        scrollToPosition(0);
                        MallObserver.getInstance().onMallDrugsLoadOnePage();
                    }
                    if (bean.getData().isNextPage()) {
                        setLoadingMoreEnabled(true);
                    } else {
                        setLoadingMoreEnabled(false);
                    }
                } else if (bean != null && !TextUtils.isEmpty(bean.getMsg())) {
                    ToastUtils.showShort(bean.getMsg());
                    if (pageStart == 1) {
                        scrollToPosition(0);
                        MallObserver.getInstance().onMallDrugsLoadOnePage();
                    }
                }

            }

            @Override
            public void onFailure(String s, int i) {
                if (pageStart == 1) {
                    scrollToPosition(0);
                    MallObserver.getInstance().onMallDrugsLoadOnePage();
                }
                LoadingUtils.getLoadingUtils(context).dismissLoading();
            }
        });
    }


    private boolean isDrugsTlFixed = false;

    public void setDrugsTlFixed(boolean drugsTlFixed) {
        isDrugsTlFixed = drugsTlFixed;
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        ALog.e("oakkk", "child on touch event: " + ev.getAction());
        if (!isDrugsTlFixed) {
            super.onTouchEvent(ev);
            getParent().requestDisallowInterceptTouchEvent(false);
            return false;
        }
        return super.onTouchEvent(ev);
    }

    @Override
    public void onRefresh() {

    }

    @Override
    public void onLoadMore() {
        pageStart++;
        getMallDrug(this.id);
    }

    private class MallDrugAdapter extends Adapter {

        private Context context;
        private List<HomeDrugEntity.DrugItemData> drugs = new ArrayList<>();

        public MallDrugAdapter(Context context, List<HomeDrugEntity.DrugItemData> drugs) {
            this.context = context;
            this.drugs = drugs;
        }

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(context).inflate(R.layout.item_mall_drug, parent, false);
            return new MallDrugVH(view);
        }

        @Override
        public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
            if (holder instanceof MallDrugVH) {
                ((MallDrugVH) holder).setData(position);
            }
        }

        @Override
        public int getItemCount() {
            return ListUtil.getSize(drugs);
        }

        private class MallDrugVH extends ViewHolder {

            ImageView drugIv;
            LinearLayout tagLl;
            TextView drugNameTv;
            TextView drugNameTv2;
            TextView rxTv;
            TextView discountTv;
            TextView priceTv;
            TextView oldPriceTv;
            FrameLayout nameFl;
            View fugouIIv;
            TextView tv_reduceRule, tv_supportGive;

            public MallDrugVH(@NonNull View itemView) {
                super(itemView);

                drugIv = itemView.findViewById(R.id.iv_drug);
                tagLl = itemView.findViewById(R.id.ll_tag);
                drugNameTv = itemView.findViewById(R.id.tv_drug_name);
                drugNameTv2 = itemView.findViewById(R.id.tv_drug_name_2);
                rxTv = itemView.findViewById(R.id.tv_rx);
                discountTv = itemView.findViewById(R.id.tv_discount);
                priceTv = itemView.findViewById(R.id.tv_price);
                oldPriceTv = itemView.findViewById(R.id.tv_old_price);
                nameFl = itemView.findViewById(R.id.fl_name_2);
                fugouIIv = itemView.findViewById(R.id.iv_fugou);
                tv_supportGive = itemView.findViewById(R.id.tv_supportGive);
                tv_reduceRule = itemView.findViewById(R.id.tv_reduceRule);
            }


            public void setData(int position) {
                if (ListUtil.getSize(drugs) > position) {
                    HomeDrugEntity.DrugItemData drug = drugs.get(position);
                    GlideUtil.load(context, drug.getImageUrl() + AllStringConstants.imgZipStr, drugIv, R.drawable.icon_default_square);

                    if (drug.isRegular()) {
                        drugNameTv.setVisibility(View.GONE);
                        nameFl.setVisibility(View.VISIBLE);
                        drugNameTv2.setText(String.format(context.getResources().getString(R.string.space_start_3), drug.getName()));
                    } else {
                        nameFl.setVisibility(View.GONE);
                        drugNameTv.setVisibility(View.VISIBLE);
                        drugNameTv.setText(drug.getName());
                    }
                    if (drug.isSupportReduce() && drug.getReduceRule() != null) {
                        tv_reduceRule.setVisibility(View.VISIBLE);
                        tv_reduceRule.setText("满" + drug.getReduceRule().getFullReduceRuleMoney() + "减" + drug.getReduceRule().getReduceMoney());
                    } else {
                        tv_reduceRule.setVisibility(View.GONE);
                    }
                    if (drug.isSupportGive()) {
                        tv_supportGive.setVisibility(View.VISIBLE);
                    } else {
                        tv_supportGive.setVisibility(View.GONE);
                    }
                    if ("1".equals(drug.getIsGiveCoupon())) {
                        fugouIIv.setVisibility(View.VISIBLE);
                    } else {
                        fugouIIv.setVisibility(View.GONE);

                    }

                    String price = "¥" + getPrice(drug.getPrice());
                    SpannableString priceSpan = new SpannableString(price);
                    priceSpan.setSpan(new RelativeSizeSpan(1.5f), 1, price.indexOf("."), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    priceTv.setText(priceSpan);

                    oldPriceTv.setPaintFlags(oldPriceTv.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
                    if (!TextUtils.isEmpty(drug.getOriginalPrice()) && Double.parseDouble(drug.getOriginalPrice()) > 0) {
                        oldPriceTv.setText("¥" + getPrice(drug.getOriginalPrice()));
                        oldPriceTv.setVisibility(View.VISIBLE);
                    } else {
                        oldPriceTv.setText("");
                        oldPriceTv.setVisibility(View.GONE);
                    }

                    ClickUtils.setFastOnClickListener(itemView, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            ClickUtils.sendEvent(ClickApi.Mall.click_drugslist, context, "电商首页药品列表点击");
                            Bundle bundle = new Bundle();

                            if ("drug".equals(drug.getCommodityType())) {
//                                bundle.putString("id", "" + drug.getDrugId());
                                bundle.putString("id", "" + drug.getCommodityId());
                            } else {
//                                bundle.putString("packetId", "" + drug.getPacketId());
                                bundle.putString("packetId", "" + drug.getCommodityId());
                            }
                            if (!TextUtils.isEmpty(doctorId)){
                                bundle.putString("doctorId", "" + doctorId);
                            }
                            ALog.e("oakkk", "bundle: " + bundle.toString());
                            MallUtils.push(context,
                                    KitArouterConstants.CART_DOCTORBUNDLE,
                                    KitArouterConstants.Cart.DrugDetail,
                                    bundle);
                        }
                    });

                }
            }

        }

    }

    private String getPrice(String price) {
        float f = Float.parseFloat(price);
        DecimalFormat decimalFormat = new DecimalFormat(".00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
        String p = decimalFormat.format(f);//format 返回的是字符串
        if (p.substring(0, 1).equals(".")) {
            p = "0" + p;
        }
        return p;
    }
}
